//
//  StudentsInfo.swift
//  StudentPerformance
//
//  Created by ap0stader on 2023/11/2.
//

import UIKit
import CoreData

class StudentsInfo {
    
    var studentsCollection : [NSManagedObject] = []
    
    private let persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "StudentPerformance")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    } ()
    
    func saveStudents() -> Bool {
        let managedContext = persistentContainer.viewContext
        if managedContext.hasChanges {
            do {
                try managedContext.save()
            } catch {
                let nsError = error as NSError
                print("Errorin saving data!", nsError.localizedDescription)
            }
        }
        return true
    }
    
    init() {
        let managedContext = persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Student")
        do {
            studentsCollection = try managedContext.fetch(fetchRequest)
        } catch let error as NSError {
            print("Cound not fetch. \(error), \(error.userInfo)")
        }
    }
    
    func addStudent(name: String, id:String, score:Int) -> Student{
        let managedContext = persistentContainer.viewContext
        let entity = NSEntityDescription.entity(forEntityName: "Student", in: managedContext)!
        let theStudent = NSManagedObject(entity: entity, insertInto: managedContext)
        
        theStudent.setValue(name, forKey: "name")
        theStudent.setValue(id, forKey: "id")
        theStudent.setValue(score, forKey: "score")
        
        studentsCollection.append(theStudent)
        return theStudent as! Student
    }
    
    func deleteStudent(_ theStudent: Student) {
        if let theIndex = studentsCollection.firstIndex(of: theStudent) {
            studentsCollection.remove(at: theIndex)
            let managedContext = persistentContainer.viewContext
            managedContext.delete(theStudent)
        }
    }
    
    func transferPosition(sourceIndex: Int, destinationIndex: Int) {
        let theStudent = studentsCollection[sourceIndex]
        studentsCollection.remove(at: sourceIndex)
        studentsCollection.insert(theStudent, at: destinationIndex)
    }
}
